/*
  ______                              _
 / _____)             _              | |
( (____  _____ ____ _| |_ _____  ____| |__
 \____ \| ___ |    (_   _) ___ |/ ___)  _ \
 _____) ) ____| | | || |_| ____( (___| | | |
(______/|_____)_|_|_| \__)_____)\____)_| |_|
    (C)2017 Semtech

Description: Generic SX126x driver implementation

License: Revised BSD License, see LICENSE.TXT file include in the project

Authors: Miguel Luis, Gregory Cristian
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "sx126x.h"
#include "sx126x-hal.h"
#include "string.h"

#include "py/runtime.h"
/*!
 * \brief Radio registers definition
 */
typedef struct
{
    uint16_t      Addr;                             //!< The address of the register
    uint8_t       Value;                            //!< The value of the register
}RadioRegisters_t;

/*!
 * \brief Stores the last frequency error measured on LoRa received packet
 */
volatile uint32_t FrequencyError = 0;

/*!
 * \brief Hold the status of the Image calibration
 */
static bool ImageCalibrated = false;

/*!
 * \brief Holds the internal operating mode of the radio
 */
RadioOperatingModes_t OperatingMode;

/*!
 * \brief Stores the current packet type set in the radio
 */
RadioPacketTypes_t PacketType;

/*!
 * \brief Holds a flag raised on radio interrupt
 */
bool IrqState;

/*!
 * \brief Hardware DIO IRQ functions
 */
DioIrqHandler dioIrq;

/*!
 * \brief Holds the polling state of the driver
 */
bool PollingMode;

extern RadioCallbacks_t callbacks;


void sx1262_Init( void )
{
    CalibrationParams_t calibParam;
    
    Reset( );

    Wakeup( );
    sx1262_SetStandby( STDBY_RC );

    sx1262_SetDio3AsTcxoCtrl( TCXO_CTRL_1_7V, 320 ); //5 ms
	calibParam.Value = 0x7F;
	sx1262_Calibrate( calibParam );

	sx1262_SetPollingMode( );

	sx1262_SetDio2AsRfSwitchCtrl( true );
    
    OperatingMode = MODE_STDBY_RC;
    
    sx1262_SetPacketType( PACKET_TYPE_LORA );

    // Change LoRa modem SyncWord for Private Networks
    WriteReg( REG_LR_SYNCWORD, ( LORA_MAC_PRIVATE_SYNCWORD >> 8 ) & 0xFF );
    WriteReg( REG_LR_SYNCWORD + 1, LORA_MAC_PRIVATE_SYNCWORD & 0xFF );
}

RadioOperatingModes_t sx1262_GetOperatingMode( void )
{
    return OperatingMode;
}

void sx1262_CheckDeviceReady( void )
{
    if( ( sx1262_GetOperatingMode( ) == MODE_SLEEP ) || ( sx1262_GetOperatingMode( ) == MODE_RX_DC ) )
    {
        Wakeup( );
        // Switch is turned off when device is in sleep mode and turned on is all other modes
//        AntSwOn( );
    }
}

void sx1262_SetPayload( uint8_t *payload, uint8_t size )
{
    WriteBuffer( 0x00, payload, size );
}

// TODO: SetPayload by DMA

uint8_t sx1262_GetPayload( uint8_t *buffer, uint8_t *size,  uint8_t maxSize )
{
    uint8_t offset = 0;

    sx1262_GetRxBufferStatus( size, &offset );
    if( *size > maxSize )
    {
        return 1;
    }
    if (*size > 0)
    {
        ReadBuffer( offset, buffer, *size );
    }
    return 0;
}

// TODO: GetPayload by DMA

void sx1262_SendPayload( uint8_t *payload, uint8_t size, uint32_t timeout )
{
	sx1262_SetPayload( payload, size );
	sx1262_SetTx( timeout );
}

uint8_t sx1262_SetSyncWord( uint8_t *syncWord )
{
    WriteRegister( REG_LR_SYNCWORDBASEADDRESS, syncWord, 8 );
    return 0;
}

void sx1262_SetCrcSeed( uint16_t seed )
{
    uint8_t buf[2];

    buf[0] = ( uint8_t )( ( seed >> 8 ) & 0xFF );
    buf[1] = ( uint8_t )( seed & 0xFF );

    switch( sx1262_GetPacketType( ) )
    {
        case PACKET_TYPE_GFSK:
            WriteRegister( REG_LR_CRCSEEDBASEADDR, buf, 2 );
            break;

        default:
            break;
    }
}

void sx1262_SetCrcPolynomial( uint16_t polynomial )
{
    uint8_t buf[2];

    buf[0] = ( uint8_t )( ( polynomial >> 8 ) & 0xFF );
    buf[1] = ( uint8_t )( polynomial & 0xFF );

    switch( sx1262_GetPacketType( ) )
    {
        case PACKET_TYPE_GFSK:
            WriteRegister( REG_LR_CRCPOLYBASEADDR, buf, 2 );
            break;

        default:
            break;
    }
}

void sx1262_SetWhiteningSeed( uint16_t seed )
{
    uint8_t regValue = 0;

    switch( sx1262_GetPacketType( ) )
    {
        case PACKET_TYPE_GFSK:
            regValue = ReadReg( REG_LR_WHITSEEDBASEADDR_MSB ) & 0xFE;
            regValue = ( ( seed >> 8 ) & 0x01 ) | regValue;
            WriteReg( REG_LR_WHITSEEDBASEADDR_MSB, regValue ); // only 1 bit.
            WriteReg( REG_LR_WHITSEEDBASEADDR_LSB, ( uint8_t )seed );
            break;

        default:
            break;
    }
}

uint32_t sx1262_GetRandom( void )
{
    uint8_t buf[] = { 0, 0, 0, 0 };

    // Set radio in continuous reception
    sx1262_SetRx( 0 );

    // HAL_Delay( 1 );

    ReadRegister( RANDOM_NUMBER_GENERATORBASEADDR, buf, 4 );

    sx1262_SetStandby( STDBY_RC );

    return ( buf[0] << 24 ) | ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3];
}

void sx1262_SetSleep( SleepParams_t sleepConfig )
{
#ifdef ADV_DEBUG
    printf("SetSleep ");
#endif

//    AntSwOff( );

    WriteCommand( RADIO_SET_SLEEP, &sleepConfig.Value, 1 );
    OperatingMode = MODE_SLEEP;
}

void sx1262_SetStandby( RadioStandbyModes_t standbyConfig )
{
#ifdef ADV_DEBUG
    printf("SetStandby ");
#endif
    WriteCommand( RADIO_SET_STANDBY, ( uint8_t* )&standbyConfig, 1 );
    if( standbyConfig == STDBY_RC )
    {
        OperatingMode = MODE_STDBY_RC;
    }
    else
    {
        OperatingMode = MODE_STDBY_XOSC;
    }
}

void sx1262_SetFs( void )
{
#ifdef ADV_DEBUG
    printf("SetFs ");
#endif
    WriteCommand( RADIO_SET_FS, 0, 0 );
    OperatingMode = MODE_FS;
}

void sx1262_SetTx( uint32_t timeout )
{
    uint8_t buf[3];

    OperatingMode = MODE_TX;
 
#ifdef ADV_DEBUG
    printf("SetTx ");
#endif

    buf[0] = ( uint8_t )( ( timeout >> 16 ) & 0xFF );
    buf[1] = ( uint8_t )( ( timeout >> 8 ) & 0xFF );
    buf[2] = ( uint8_t )( timeout & 0xFF );
    WriteCommand( RADIO_SET_TX, buf, 3 );
}

void sx1262_SetRxBoosted( uint32_t timeout )
{
    uint8_t buf[3];

    OperatingMode = MODE_RX;

#ifdef ADV_DEBUG
    printf("SetRxBoosted ");
#endif

    WriteReg( REG_RX_GAIN, 0x96 ); // max LNA gain, increase current by ~2mA for around ~3dB in sensivity

    buf[0] = ( uint8_t )( ( timeout >> 16 ) & 0xFF );
    buf[1] = ( uint8_t )( ( timeout >> 8 ) & 0xFF );
    buf[2] = ( uint8_t )( timeout & 0xFF );
    WriteCommand( RADIO_SET_RX, buf, 3 );
}

void sx1262_SetRx( uint32_t timeout )
{
    uint8_t buf[3];

    OperatingMode = MODE_RX;

#ifdef ADV_DEBUG
    printf("SetRx ");
#endif

    buf[0] = ( uint8_t )( ( timeout >> 16 ) & 0xFF );
    buf[1] = ( uint8_t )( ( timeout >> 8 ) & 0xFF );
    buf[2] = ( uint8_t )( timeout & 0xFF );
    WriteCommand( RADIO_SET_RX, buf, 3 );
}

void sx1262_SetRxDutyCycle( uint32_t rxTime, uint32_t sleepTime )
{
    uint8_t buf[6];

    buf[0] = ( uint8_t )( ( rxTime >> 16 ) & 0xFF );
    buf[1] = ( uint8_t )( ( rxTime >> 8 ) & 0xFF );
    buf[2] = ( uint8_t )( rxTime & 0xFF );
    buf[3] = ( uint8_t )( ( sleepTime >> 16 ) & 0xFF );
    buf[4] = ( uint8_t )( ( sleepTime >> 8 ) & 0xFF );
    buf[5] = ( uint8_t )( sleepTime & 0xFF );
    WriteCommand( RADIO_SET_RXDUTYCYCLE, buf, 6 );
    OperatingMode = MODE_RX_DC;
}

void sx1262_SetCad( void )
{
    WriteCommand( RADIO_SET_CAD, 0, 0 );
    OperatingMode = MODE_CAD;
}

void sx1262_SetTxContinuousWave( void )
{
#ifdef ADV_DEBUG
    printf("SetTxContinuousWave ");
#endif
    WriteCommand( RADIO_SET_TXCONTINUOUSWAVE, 0, 0 );
}

void sx1262_SetTxInfinitePreamble( void )
{
#ifdef ADV_DEBUG
    printf("SetTxContinuousPreamble ");
#endif
    WriteCommand( RADIO_SET_TXCONTINUOUSPREAMBLE, 0, 0 );
}

void sx1262_SetStopRxTimerOnPreambleDetect( bool enable )
{
    WriteCommand( RADIO_SET_STOPRXTIMERONPREAMBLE, ( uint8_t* )&enable, 1 );
}

void sx1262_SetLoRaSymbNumTimeout( uint8_t SymbNum )
{
    WriteCommand( RADIO_SET_LORASYMBTIMEOUT, &SymbNum, 1 );
}

void sx1262_SetRegulatorMode( RadioRegulatorMode_t mode )
{
#ifdef ADV_DEBUG
    printf("SetRegulatorMode ");
#endif
    WriteCommand( RADIO_SET_REGULATORMODE, ( uint8_t* )&mode, 1 );
}

void sx1262_Calibrate( CalibrationParams_t calibParam )
{
    WriteCommand( RADIO_CALIBRATE, &calibParam.Value, 1 );
}

void sx1262_CalibrateImage( uint32_t freq )
{
	uint8_t calFreq[2];

	// only 433 band
	calFreq[0] = 0x6B;
	calFreq[1] = 0x6F;
    WriteCommand( RADIO_CALIBRATEIMAGE, calFreq, 2 );
}

void sx1262_SetPaConfig( uint8_t paDutyCycle, uint8_t HpMax, uint8_t deviceSel, uint8_t paLUT )
{
    uint8_t buf[4];

#ifdef ADV_DEBUG
    printf("SetPaConfig ");
#endif

    buf[0] = paDutyCycle;
    buf[1] = HpMax;
    buf[2] = deviceSel;
    buf[3] = paLUT;
    WriteCommand( RADIO_SET_PACONFIG, buf, 4 );
}

void sx1262_SetRxTxFallbackMode( uint8_t fallbackMode )
{
    WriteCommand( RADIO_SET_TXFALLBACKMODE, &fallbackMode, 1 );
}

void sx1262_SetDioIrqParams( uint16_t irqMask, uint16_t dio1Mask, uint16_t dio2Mask, uint16_t dio3Mask )
{
    uint8_t buf[8];

#ifdef ADV_DEBUG
    printf("SetDioIrqParams ");
#endif

    buf[0] = ( uint8_t )( ( irqMask >> 8 ) & 0x00FF );
    buf[1] = ( uint8_t )( irqMask & 0x00FF );
    buf[2] = ( uint8_t )( ( dio1Mask >> 8 ) & 0x00FF );
    buf[3] = ( uint8_t )( dio1Mask & 0x00FF );
    buf[4] = ( uint8_t )( ( dio2Mask >> 8 ) & 0x00FF );
    buf[5] = ( uint8_t )( dio2Mask & 0x00FF );
    buf[6] = ( uint8_t )( ( dio3Mask >> 8 ) & 0x00FF );
    buf[7] = ( uint8_t )( dio3Mask & 0x00FF );
    WriteCommand( RADIO_CFG_DIOIRQ, buf, 8 );
}

uint16_t sx1262_GetIrqStatus( void )
{
    uint8_t irqStatus[2];

    ReadCommand( RADIO_GET_IRQSTATUS, irqStatus, 2 );
    return ( irqStatus[0] << 8 ) | irqStatus[1];
}

void sx1262_SetDio2AsRfSwitchCtrl( uint8_t enable )
{
#ifdef ADV_DEBUG
    printf("SetDio2AsRfSwitchCtrl ");
#endif
    WriteCommand( RADIO_SET_RFSWITCHMODE, &enable, 1 );
}

void sx1262_SetDio3AsTcxoCtrl( RadioTcxoCtrlVoltage_t tcxoVoltage, uint32_t timeout )
{
    uint8_t buf[4];

    buf[0] = tcxoVoltage & 0x07;
    buf[1] = ( uint8_t )( ( timeout >> 16 ) & 0xFF );
    buf[2] = ( uint8_t )( ( timeout >> 8 ) & 0xFF );
    buf[3] = ( uint8_t )( timeout & 0xFF );

    WriteCommand( RADIO_SET_TCXOMODE, buf, 4 );
}

void sx1262_SetRfFrequency( uint32_t frequency )
{
    uint8_t buf[4];
    uint32_t freq = 0;

#ifdef ADV_DEBUG
    printf("SetRfFrequency ");
#endif

    if( ImageCalibrated == false )
    {
    	sx1262_CalibrateImage( frequency );
        ImageCalibrated = true;
    }

    freq = ( uint32_t )( ( double )frequency / ( double )FREQ_STEP );
    buf[0] = ( uint8_t )( ( freq >> 24 ) & 0xFF );
    buf[1] = ( uint8_t )( ( freq >> 16 ) & 0xFF );
    buf[2] = ( uint8_t )( ( freq >> 8 ) & 0xFF );
    buf[3] = ( uint8_t )( freq & 0xFF );
    WriteCommand( RADIO_SET_RFFREQUENCY, buf, 4 );
}

void sx1262_SetPacketType( RadioPacketTypes_t packetType )
{
#ifdef ADV_DEBUG
    printf("SetPacketType ");
#endif

    // Save packet type internally to avoid questioning the radio
    PacketType = packetType;
    WriteCommand( RADIO_SET_PACKETTYPE, ( uint8_t* )&packetType, 1 );
}

RadioPacketTypes_t sx1262_GetPacketType( void )
{
    return PacketType;
}

void sx1262_SetTxParams( int8_t power, RadioRampTimes_t rampTime )
{
    uint8_t buf[2];

#ifdef ADV_DEBUG
    printf("SetTxParams ");
#endif

    sx1262_SetPaConfig( 0x04, 0x07, 0x00, 0x01 );
    // sx1262_SetPaConfig( 0x02, 0x03, 0x00, 0x01 );
	if( power > 22 )
	{
		power = 22;
	}
	else if( power < -3 )
	{
		power = -3;
	}
	WriteReg( REG_OCP, 0x38 ); // current max 160mA for the whole device

    buf[0] = power;

    // TCXO
	if( ( uint8_t )rampTime < RADIO_RAMP_200_US )
	{
		buf[1] = RADIO_RAMP_200_US;
	}
	else
	{
		buf[1] = ( uint8_t )rampTime;
	}

    WriteCommand( RADIO_SET_TXPARAMS, buf, 2 );
}

void sx1262_SetModulationParams( ModulationParams_t *modulationParams )
{
    uint8_t n;
    uint32_t tempVal = 0;
    uint8_t buf[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

#ifdef ADV_DEBUG
    printf("SetModulationParams ");
#endif

    // Check if required configuration corresponds to the stored packet type
    // If not, silently update radio packet type
    if( PacketType != modulationParams->PacketType )
    {
    	sx1262_SetPacketType( modulationParams->PacketType );
    }

    switch( modulationParams->PacketType )
    {
    case PACKET_TYPE_GFSK:
        n = 8;
        tempVal = ( uint32_t )( 32 * ( ( double )XTAL_FREQ / ( double )modulationParams->Params.Gfsk.BitRate ) );
        buf[0] = ( tempVal >> 16 ) & 0xFF;
        buf[1] = ( tempVal >> 8 ) & 0xFF;
        buf[2] = tempVal & 0xFF;
        buf[3] = modulationParams->Params.Gfsk.ModulationShaping;
        buf[4] = modulationParams->Params.Gfsk.Bandwidth;
        tempVal = ( uint32_t )( ( double )modulationParams->Params.Gfsk.Fdev / ( double )FREQ_STEP );
        buf[5] = ( tempVal >> 16 ) & 0xFF;
        buf[6] = ( tempVal >> 8 ) & 0xFF;
        buf[7] = ( tempVal& 0xFF );
        break;
    case PACKET_TYPE_LORA:
        n = 4;
        switch( modulationParams->Params.LoRa.Bandwidth )
        {
            case LORA_BW_500:
                 modulationParams->Params.LoRa.LowDatarateOptimize = 0x00;
                break;
            case LORA_BW_250:
                if( modulationParams->Params.LoRa.SpreadingFactor == 12 )
                {
                    modulationParams->Params.LoRa.LowDatarateOptimize = 0x01;
                }
                else
                {
                    modulationParams->Params.LoRa.LowDatarateOptimize = 0x00;
                }
                break;
            case LORA_BW_125:
                if( modulationParams->Params.LoRa.SpreadingFactor >= 11 )
                {
                    modulationParams->Params.LoRa.LowDatarateOptimize = 0x01;
                }
                else
                {
                    modulationParams->Params.LoRa.LowDatarateOptimize = 0x00;
                }
                break;
            case LORA_BW_062:
                if( modulationParams->Params.LoRa.SpreadingFactor >= 10 )
                {
                    modulationParams->Params.LoRa.LowDatarateOptimize = 0x01;
                }
                else
                {
                    modulationParams->Params.LoRa.LowDatarateOptimize = 0x00;
                }
                break;
            case LORA_BW_041:
                if( modulationParams->Params.LoRa.SpreadingFactor >= 9 )
                {
                    modulationParams->Params.LoRa.LowDatarateOptimize = 0x01;
                }
                else
                {
                    modulationParams->Params.LoRa.LowDatarateOptimize = 0x00;
                }
                break;
            case LORA_BW_031:
            case LORA_BW_020:
            case LORA_BW_015:
            case LORA_BW_010:
            case LORA_BW_007:
                    modulationParams->Params.LoRa.LowDatarateOptimize = 0x01;
                break;
            default:
                break;
        }
        buf[0] = modulationParams->Params.LoRa.SpreadingFactor;
        buf[1] = modulationParams->Params.LoRa.Bandwidth;
        buf[2] = modulationParams->Params.LoRa.CodingRate;
        buf[3] = modulationParams->Params.LoRa.LowDatarateOptimize;
        break;
    default:
    case PACKET_TYPE_NONE:
        return;
    }
    WriteCommand( RADIO_SET_MODULATIONPARAMS, buf, n );
}

void sx1262_SetPacketParams( PacketParams_t *packetParams )
{
    uint8_t n;
//    uint8_t crcVal = 0;
    uint8_t buf[9] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

#ifdef ADV_DEBUG
    printf("SetPacketParams ");
#endif

    // Check if required configuration corresponds to the stored packet type
    // If not, silently update radio packet type
    if( PacketType != packetParams->PacketType )
    {
    	sx1262_SetPacketType( packetParams->PacketType );
    }

    switch( packetParams->PacketType )
    {
    	// Save flash space
//    case PACKET_TYPE_GFSK:
//        if( packetParams->Params.Gfsk.CrcLength == RADIO_CRC_2_BYTES_IBM )
//        {
//        	sx1262_SetCrcSeed( CRC_IBM_SEED );
//        	sx1262_SetCrcPolynomial( CRC_POLYNOMIAL_IBM );
//            crcVal = RADIO_CRC_2_BYTES;
//        }
//        else if(  packetParams->Params.Gfsk.CrcLength == RADIO_CRC_2_BYTES_CCIT )
//        {
//        	sx1262_SetCrcSeed( CRC_CCITT_SEED );
//        	sx1262_SetCrcPolynomial( CRC_POLYNOMIAL_CCITT );
//            crcVal = RADIO_CRC_2_BYTES_INV;
//        }
//        else
//        {
//            crcVal = packetParams->Params.Gfsk.CrcLength;
//        }
//        n = 9;
//        // convert preamble length from byte to bit
//        packetParams->Params.Gfsk.PreambleLength = packetParams->Params.Gfsk.PreambleLength << 3;
//
//        buf[0] = ( packetParams->Params.Gfsk.PreambleLength >> 8 ) & 0xFF;
//        buf[1] = packetParams->Params.Gfsk.PreambleLength;
//        buf[2] = packetParams->Params.Gfsk.PreambleMinDetect;
//        buf[3] = ( packetParams->Params.Gfsk.SyncWordLength << 3 ); // convert from byte to bit
//        buf[4] = packetParams->Params.Gfsk.AddrComp;
//        buf[5] = packetParams->Params.Gfsk.HeaderType;
//        buf[6] = packetParams->Params.Gfsk.PayloadLength;
//        buf[7] = crcVal;
//        buf[8] = packetParams->Params.Gfsk.DcFree;
//        break;
    case PACKET_TYPE_LORA:
        n = 6;
        buf[0] = ( packetParams->Params.LoRa.PreambleLength >> 8 ) & 0xFF;
        buf[1] = packetParams->Params.LoRa.PreambleLength;
        buf[2] = packetParams->Params.LoRa.HeaderType;
        buf[3] = packetParams->Params.LoRa.PayloadLength;
        buf[4] = packetParams->Params.LoRa.CrcMode;
        buf[5] = packetParams->Params.LoRa.InvertIQ;
        break;
    default:
    case PACKET_TYPE_NONE:
        return;
    }
    WriteCommand( RADIO_SET_PACKETPARAMS, buf, n );
}

void sx1262_SetCadParams( RadioLoRaCadSymbols_t cadSymbolNum, uint8_t cadDetPeak, uint8_t cadDetMin, RadioCadExitModes_t cadExitMode, uint32_t cadTimeout )
{
    uint8_t buf[7];

    buf[0] = ( uint8_t )cadSymbolNum;
    buf[1] = cadDetPeak;
    buf[2] = cadDetMin;
    buf[3] = ( uint8_t )cadExitMode;
    buf[4] = ( uint8_t )( ( cadTimeout >> 16 ) & 0xFF );
    buf[5] = ( uint8_t )( ( cadTimeout >> 8 ) & 0xFF );
    buf[6] = ( uint8_t )( cadTimeout & 0xFF );
    WriteCommand( RADIO_SET_CADPARAMS, buf, 7 );
    OperatingMode = MODE_CAD;
}

void sx1262_SetBufferBaseAddresses( uint8_t txBaseAddress, uint8_t rxBaseAddress )
{
    uint8_t buf[2];

#ifdef ADV_DEBUG
    printf("SetBufferBaseAddresses ");
#endif

    buf[0] = txBaseAddress;
    buf[1] = rxBaseAddress;
    WriteCommand( RADIO_SET_BUFFERBASEADDRESS, buf, 2 );
}

RadioStatus_t sx1262_GetStatus( void )
{
    uint8_t stat = 0;
    RadioStatus_t status;

    ReadCommand( RADIO_GET_STATUS, ( uint8_t * )&stat, 1 );
    status.Value = stat;
    return status;
}

int8_t sx1262_GetRssiInst( void )
{
    uint8_t rssi;

    ReadCommand( RADIO_GET_RSSIINST, ( uint8_t* )&rssi, 1 );
    return( -( rssi / 2 ) );
}

void sx1262_GetRxBufferStatus( uint8_t *payloadLength, uint8_t *rxStartBufferPointer )
{
    uint8_t status[2];

    ReadCommand( RADIO_GET_RXBUFFERSTATUS, status, 2 );

    // In case of LORA fixed header, the payloadLength is obtained by reading
    // the register REG_LR_PAYLOADLENGTH
    // 这段代码应该是给固定长度应用使用，但是寄存器读取可能出现问题。（优化：理论上不需要每次读取寄存器的，直接带内存中保留当前芯片工作模式即可，避免浪费时间读取）
//    if( ( sx1262_GetPacketType( ) == PACKET_TYPE_LORA ) && ( ReadReg( REG_LR_PACKETPARAMS ) >> 7 == 1 ) )
//    {
//        *payloadLength = ReadReg( REG_LR_PAYLOADLENGTH );
//    }
//    else
//    {
//        *payloadLength = status[0];
//    }

    *payloadLength = status[0];
    *rxStartBufferPointer = status[1];
}

void sx1262_GetPacketStatus( PacketStatus_t *pktStatus )
{
    uint8_t status[3];

    ReadCommand( RADIO_GET_PACKETSTATUS, status, 3 );

    pktStatus->packetType = sx1262_GetPacketType( );
    switch( pktStatus->packetType )
    {
        case PACKET_TYPE_GFSK:
            pktStatus->Params.Gfsk.RxStatus = status[0];
            pktStatus->Params.Gfsk.RssiSync = -status[1] / 2;
            pktStatus->Params.Gfsk.RssiAvg = -status[2] / 2;
            pktStatus->Params.Gfsk.FreqError = 0;
            break;

        case PACKET_TYPE_LORA:
            pktStatus->Params.LoRa.RssiPkt = -status[0] / 2;
            ( status[1] < 128 ) ? ( pktStatus->Params.LoRa.SnrPkt = status[1] / 4 ) : ( pktStatus->Params.LoRa.SnrPkt = ( ( status[1] - 256 ) /4 ) );
            pktStatus->Params.LoRa.SignalRssiPkt = -status[2] / 2;
            pktStatus->Params.LoRa.FreqError = FrequencyError;
            break;

        default:
        case PACKET_TYPE_NONE:
            // In that specific case, we set everything in the pktStatus to zeros
            // and reset the packet type accordingly
            memset( pktStatus, 0, sizeof( PacketStatus_t ) );
            pktStatus->packetType = PACKET_TYPE_NONE;
            break;
    }
}

RadioError_t sx1262_GetDeviceErrors( void )
{
    RadioError_t error;

    ReadCommand( RADIO_GET_ERROR, ( uint8_t * )&error, 2 );
    return error;
}

void sx1262_ClearIrqStatus( uint16_t irq )
{
    uint8_t buf[2];
#ifdef ADV_DEBUG
    printf("ClearIrqStatus ");
#endif
    buf[0] = ( uint8_t )( ( ( uint16_t )irq >> 8 ) & 0x00FF );
    buf[1] = ( uint8_t )( ( uint16_t )irq & 0x00FF );
    WriteCommand( RADIO_CLR_IRQSTATUS, buf, 2 );
}

void sx1262_SetPollingMode( void )
{
    PollingMode = true;
}

void sx1262_SetInterruptMode( void )
{
    PollingMode = false;
}

//void sx1262_OnDioIrq( void )
//{
//    /*
//     * When polling mode is activated, it is up to the application to call
//     * ProcessIrqs( ). Otherwise, the driver automatically calls ProcessIrqs( )
//     * on radio interrupt.
//     */
//    if( PollingMode == true )
//    {
//        IrqState = true;
//    }
//    else
//    {
//    	sx1262_ProcessIrqs( );
//    }
//}

void sx1262_ProcessIrqs( void )
{
//    if( PollingMode == true )
//    {
//        if( IrqState == true )
//        {
//            __disable_irq( );
//            IrqState = false;
//            __enable_irq( );
//        }
//        else
//        {
//            return;
//        }
//    }

    uint16_t irqRegs = sx1262_GetIrqStatus( );
    sx1262_ClearIrqStatus( IRQ_RADIO_ALL );

#ifdef ADV_DEBUG
    printf("0x%04x\n\r", irqRegs );
#endif

    if( ( irqRegs & IRQ_HEADER_VALID ) == IRQ_HEADER_VALID )
    {
        // LoRa Only
        FrequencyError = 0x000000 | ( ( 0x0F & ReadReg( REG_FREQUENCY_ERRORBASEADDR ) ) << 16 );
        FrequencyError = FrequencyError | ( ReadReg( REG_FREQUENCY_ERRORBASEADDR + 1 ) << 8 );
        FrequencyError = FrequencyError | ( ReadReg( REG_FREQUENCY_ERRORBASEADDR + 2 ) );
    }

    if( ( irqRegs & IRQ_TX_DONE ) == IRQ_TX_DONE )
    {
        if( callbacks.txDone != NULL )
        {
        	callbacks.txDone( );
        }
    }

    if( ( irqRegs & IRQ_RX_DONE ) == IRQ_RX_DONE )
    {
        if( ( irqRegs & IRQ_CRC_ERROR ) == IRQ_CRC_ERROR )
        {
            if( callbacks.rxError != NULL )
            {
            	callbacks.rxError( IRQ_CRC_ERROR_CODE );
            }
        }
        else
        {
            if( callbacks.rxDone != NULL )
            {
            	callbacks.rxDone( );
            }
        }
    }

    if( ( irqRegs & IRQ_CAD_DONE ) == IRQ_CAD_DONE )
    {
        if( callbacks.cadDone != NULL )
        {
        	callbacks.cadDone( ( irqRegs & IRQ_CAD_ACTIVITY_DETECTED ) == IRQ_CAD_ACTIVITY_DETECTED );
        }
    }

    if( ( irqRegs & IRQ_RX_TX_TIMEOUT ) == IRQ_RX_TX_TIMEOUT )
    {
        if( ( callbacks.txTimeout != NULL ) && ( OperatingMode == MODE_TX ) )
        {
        	callbacks.txTimeout( );
        }
        else if( ( callbacks.rxTimeout != NULL ) && ( OperatingMode == MODE_RX ) )
        {
        	callbacks.rxTimeout( );
        }
        else
        {
            assert_param( FAIL );
        }
    }
    
/*
    //IRQ_PREAMBLE_DETECTED                   = 0x0004,
    if( irqRegs & IRQ_PREAMBLE_DETECTED )
    {
        if( rxPblSyncWordHeader != NULL )
        {
            rxPblSyncWordHeader( IRQ_PBL_DETECT_CODE);
            
        }
    }

    //IRQ_SYNCWORD_VALID                      = 0x0008,
    if( irqRegs & IRQ_SYNCWORD_VALID )
    {
        if( rxPblSyncWordHeader != NULL )
        {
            rxPblSyncWordHeader( IRQ_SYNCWORD_VALID_CODE  );
        }
    }

    //IRQ_HEADER_VALID                        = 0x0010,
    if ( irqRegs & IRQ_HEADER_VALID ) 
    {
        if( rxPblSyncWordHeader != NULL )
        {
            rxPblSyncWordHeader( IRQ_HEADER_VALID_CODE );
        }
    } 

    //IRQ_HEADER_ERROR                        = 0x0020,
    if( irqRegs & IRQ_HEADER_ERROR )
    {
        if( rxError != NULL )
        {
            rxError( IRQ_HEADER_ERROR_CODE );
        }
    }  
*/
}



/******************************************/
static PacketParams_t	PacketParams;
// static PacketStatus_t	PacketStatus;

const uint16_t RxIrqMask = IRQ_RX_DONE | IRQ_CRC_ERROR | IRQ_RX_TX_TIMEOUT;
const uint16_t TxIrqMask = IRQ_TX_DONE | IRQ_RX_TX_TIMEOUT;

#define		MAX_LORA_BUFFER_SIZE	255

STATIC mp_obj_t sx126xInit(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args)
{
	return sx126x_hal_init(n_args, args, kw_args);
}

STATIC MP_DEFINE_CONST_FUN_OBJ_KW(sx126xInit_obj, 1, sx126xInit);

STATIC mp_obj_t sx126xBegin(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args)
{
	ModulationParams_t modulationParams;

	// Parse arguments
    enum { ARG_freq, ARG_sf, ARG_bw, ARG_cr, ARG_power, ARG_pl};
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_freq,  MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 433000000} },
        { MP_QSTR_sf,    MP_ARG_INT, {.u_int = LORA_SF9} },
		{ MP_QSTR_bw,    MP_ARG_INT, {.u_int = LORA_BW_500} },
		{ MP_QSTR_cr,    MP_ARG_INT, {.u_int = LORA_CR_4_7} },
        { MP_QSTR_power, MP_ARG_INT, {.u_int = 14} },
        { MP_QSTR_pl,    MP_ARG_INT, {.u_int = 0x08} },
    };
    
    mp_arg_val_t args_val[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args, args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args_val);

	modulationParams.PacketType = PACKET_TYPE_LORA;
	modulationParams.Params.LoRa.SpreadingFactor = args_val[ARG_sf].u_int;
	modulationParams.Params.LoRa.Bandwidth = args_val[ARG_bw].u_int;
	modulationParams.Params.LoRa.CodingRate = args_val[ARG_cr].u_int;

	PacketParams.PacketType = PACKET_TYPE_LORA;
	PacketParams.Params.LoRa.PreambleLength = args_val[ARG_pl].u_int;
	PacketParams.Params.LoRa.HeaderType = LORA_PACKET_VARIABLE_LENGTH;
	PacketParams.Params.LoRa.PayloadLength = 0;
	PacketParams.Params.LoRa.CrcMode = LORA_CRC_ON;
	PacketParams.Params.LoRa.InvertIQ = LORA_IQ_NORMAL;

    sx1262_Init();

	sx1262_SetStandby(STDBY_RC);
	// sx1262_SetStandby(STDBY_XOSC);

    sx1262_SetRegulatorMode(USE_DCDC);
    
	sx1262_SetPacketType(modulationParams.PacketType);
	sx1262_SetModulationParams(&modulationParams);
	sx1262_SetPacketParams(&PacketParams);

	sx1262_SetRfFrequency( args_val[ARG_freq].u_int );
	sx1262_SetBufferBaseAddresses(0x00, 0x00);
	// sx1262_SetPaConfig(0x04, 0x07, 0x00, 0x01);
	sx1262_SetTxParams( args_val[ARG_power].u_int, RADIO_RAMP_200_US);
    // sx1262_SetTxParams( 14, RADIO_RAMP_200_US);

	sx1262_SetDioIrqParams(RxIrqMask | TxIrqMask, RxIrqMask | TxIrqMask, IRQ_RADIO_NONE, IRQ_RADIO_NONE);

	sx1262_SetLoRaSymbNumTimeout(0);

	return mp_const_none;
}

STATIC MP_DEFINE_CONST_FUN_OBJ_KW(sx126xBegin_obj, 0, sx126xBegin);

STATIC mp_obj_t sx126xSend(mp_obj_t buf_obj, mp_obj_t timeout_obj)
{
  mp_buffer_info_t buf;

  mp_get_buffer_raise(buf_obj, &buf, MP_BUFFER_READ);
  uint timeout = mp_obj_int_get_uint_checked(timeout_obj);

  PacketParams.Params.LoRa.PayloadLength = buf.len;
  sx1262_SetPacketParams(&PacketParams);

  sx1262_SendPayload((uint8_t*)buf.buf, buf.len, timeout);

  return mp_const_none;
}

STATIC MP_DEFINE_CONST_FUN_OBJ_2(sx126xSend_obj, sx126xSend);

STATIC mp_obj_t sx126xSetRX(mp_obj_t timeout_obj, mp_obj_t boost_obj)
{
  uint timeout = mp_obj_int_get_uint_checked(timeout_obj);
  bool boost = mp_obj_is_true(boost_obj);

  if (boost)
  {
	  sx1262_SetRxBoosted(timeout);
  }
  else
  {
	  sx1262_SetRx(timeout);
  }

  return mp_const_none;
}

STATIC MP_DEFINE_CONST_FUN_OBJ_2(sx126xSetRX_obj, sx126xSetRX);

STATIC mp_obj_t sx126xRecv()
{
  uint8_t	receiveBuffer[MAX_LORA_BUFFER_SIZE];
  uint8_t	receiveSize = 0;

  sx1262_GetPayload(receiveBuffer, &receiveSize, sizeof(receiveBuffer));

  return mp_obj_new_bytes(receiveBuffer, receiveSize);
}

STATIC MP_DEFINE_CONST_FUN_OBJ_0(sx126xRecv_obj, sx126xRecv);

STATIC mp_obj_t sx126xGetStatus()
{
  RadioStatus_t	s;

  s = sx1262_GetStatus();

  return mp_obj_new_int(s.Value);
}

STATIC MP_DEFINE_CONST_FUN_OBJ_0(sx126xGetStatus_obj, sx126xGetStatus);

STATIC mp_obj_t sx126xGetIrqStatus()
{
  uint16_t irqRegs = sx1262_GetIrqStatus( );
//   sx1262_ClearIrqStatus( IRQ_RADIO_ALL );   不可以清除所有，因为会有竞争冲突，导致还没有处理的中断标记被清除。读取和清除间，会有中断到达的
  sx1262_ClearIrqStatus( irqRegs );

  return mp_obj_new_int(irqRegs);
}

STATIC MP_DEFINE_CONST_FUN_OBJ_0(sx126xGetIrqStatus_obj, sx126xGetIrqStatus);

STATIC const mp_rom_map_elem_t sx126x_module_globals_table[] = {
    {MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_sx126x)},
    {MP_ROM_QSTR(MP_QSTR_Init), MP_ROM_PTR(&sx126xInit_obj)},
	{MP_ROM_QSTR(MP_QSTR_Begin), MP_ROM_PTR(&sx126xBegin_obj)},
	{MP_ROM_QSTR(MP_QSTR_Send), MP_ROM_PTR(&sx126xSend_obj)},
	{MP_ROM_QSTR(MP_QSTR_Recv), MP_ROM_PTR(&sx126xRecv_obj)},
	{MP_ROM_QSTR(MP_QSTR_SetRx), MP_ROM_PTR(&sx126xSetRX_obj)},
    {MP_ROM_QSTR(MP_QSTR_GetStatus), MP_ROM_PTR(&sx126xGetStatus_obj)},
    {MP_ROM_QSTR(MP_QSTR_GetIrqStatus), MP_ROM_PTR(&sx126xGetIrqStatus_obj)},

    // const
    { MP_ROM_QSTR(MP_QSTR_IRQ_RADIO_NONE),    MP_ROM_INT(IRQ_RADIO_NONE) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_TX_DONE), MP_ROM_INT(IRQ_TX_DONE) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_RX_DONE), MP_ROM_INT(IRQ_RX_DONE) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_PREAMBLE_DETECTED), MP_ROM_INT(IRQ_PREAMBLE_DETECTED) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_SYNCWORD_VALID), MP_ROM_INT(IRQ_SYNCWORD_VALID) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_HEADER_VALID), MP_ROM_INT(IRQ_HEADER_VALID) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_HEADER_ERROR), MP_ROM_INT(IRQ_HEADER_ERROR) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_CRC_ERROR), MP_ROM_INT(IRQ_CRC_ERROR) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_CAD_DONE), MP_ROM_INT(IRQ_CAD_DONE) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_CAD_ACTIVITY_DETECTED), MP_ROM_INT(IRQ_CAD_ACTIVITY_DETECTED) },
    { MP_ROM_QSTR(MP_QSTR_IRQ_RX_TX_TIMEOUT), MP_ROM_INT(IRQ_RX_TX_TIMEOUT) },
};
STATIC MP_DEFINE_CONST_DICT(sx126x_module_globals, sx126x_module_globals_table);

// Define module object.
const mp_obj_module_t sx126x_user_cmodule = {
    .base = {&mp_type_module},
    .globals = (mp_obj_dict_t *)&sx126x_module_globals,
};

// Register the module to make it available in Python.
MP_REGISTER_MODULE(MP_QSTR_sx126x, sx126x_user_cmodule, MODULE_SX126X_ENABLED);
